const OrdersPayService = require("../services/orderpayServices");

class OrdersPayController {
  constructor() {
    this.addNewOrder = this.addNewOrder.bind(this);
    this.deleteOrderById = this.deleteOrderById.bind(this);
    this.getOrdersByUserId = this.getOrdersByUserId.bind(this);
    this.getAllOrders = this.getAllOrders.bind(this);
    this.getLatestOrders = this.getLatestOrders.bind(this)
  }

  // 统一响应函数
  handleRequest = async (serviceMethod, req, res, successStatus = 200) => {
    try {
      const result = await serviceMethod(req);
      if (result.code === 0) {
        res.status(successStatus).json(result); // 成功
      } else {
        res.status(result.statusCode || 400).json(result); // 失败
      }
    } catch (error) {
      res.status(500).json({
        code: 1,
        msg: "服务器内部错误",
      });
    }
  };

  async addNewOrder(req, res) {
    await this.handleRequest(
      () => OrdersPayService.addNewOrder(req.body),
      req,
      res
    );
  }

  async deleteOrderById(req, res) {
    await this.handleRequest(
      () => OrdersPayService.deleteOrderById(req.params.id),
      req,
      res
    );
  }

  async getOrdersByUserId(req, res) {
    await this.handleRequest(
      () => OrdersPayService.getOrdersByUserId(req.params.userId),
      req,
      res
    );
  }

  async getAllOrders(req, res) {
    await this.handleRequest(() => OrdersPayService.getAllOrders(), req, res);
  }

  async getLatestOrders(req, res) {
    await this.handleRequest(
      () => OrdersPayService.getLatestOrders(req.params.userId),
      req,
      res
    );
  }
}

module.exports = new OrdersPayController();
